// stores/useSharedStore.ts
import { defineStore } from 'pinia'

type Bucket = {
  id: string
  name: string
}

type DatabaseInfo = {
  IP: string
  port: string
  orgId: string
  token: string
  cookies: string
  username: string
  password: string
  buckets: Bucket[]
}

type InfluxdbConfig = {
  id: string
  type: 'local' | 'remote'
  info: DatabaseInfo  // 修改字段名从 config 改为 info
}

export const useSharedStore = defineStore('shared', {
  state: () => ({
    influxdbInfos: [] as InfluxdbConfig[],  // 使用新类型
    loading: false
  }),
  actions: {
    async update_influxdb_info() {
      this.loading = true
      try {
        const response = await window.pywebview.api.get_influxdb_info()
        console.log(response)
        // 简化数据转换逻辑
        this.influxdbInfos = response.map((item: any) => ({
          id: item.id,
          type: item.type,  // 直接使用返回的type字段
          info: item.info    // 直接使用返回的info字段
        }))
      } finally {
        this.loading = false
      }
    },

    async get_config_info() {
      this.loading = true
      try {
        const response = await window.pywebview.api.get_config_info()
        console.log(response)
        this.influxdbInfos = response.map((item: any) => ({
          id: item.id,
          type: item.type,  // 直接使用type字段
          info: item.info    // 直接使用info字段
        }))
      } finally {
        this.loading = false
      }
    },

    // 添加更新方法（需要实现API）
    async update_config(id: string, newInfo: Partial<DatabaseInfo>) {
      try {
        this.loading = true
        await window.pywebview.api.update_influxdb_config()
        // {
        //   id,
        //   info: newInfo
        // }
        await this.get_config_info() // 刷新数据
      } finally {
        this.loading = false
      }
    }
  }
})
